<?php #ajax Редактирование страниц из базы данных
	$errors = array();
	switch($_POST['action']) {
		case 'edit_table':
			if( $_POST['data'] ) {
				$array_in_rows = array_chunk($_POST['data'], $_POST['quantity']);

				foreach( $array_in_rows as $i => $data ) {
					$sql = "update {$_POST['table']} set ";
					
					foreach( $data as $i => $data_info ) {
						if( $data_info['name'] == $_POST['main_column'] ) {
							$cur_main_col_val = $data_info['value'];
							
							$sql .= $data_info['name'] ."=". "'{$data_info['value']}', ";
							continue;
						}
						$sql .= $data_info['name'] ."=". "'{$data_info['value']}', ";
					}
					
					$sql = substr($sql, 0, -2)." where {$_POST['main_column']} = {$cur_main_col_val};";
					$conn->query($sql);
				}

				echo json_encode( array( 'errors' => $errors , 'data' => $_POST['data'] ) );	
			}
		break;	
		case 'del_row':
			$conn->query("DELETE FROM {$_POST['table']} WHERE {$_POST['main_column']} = '{$_POST['main_column_val']}' limit 1");
			echo json_encode( array( 'errors' => $errors , 'val' => $_POST['main_column'] ) );
		break;	
		
		case 'add_new_rows':
			if( $_POST['data'] ) {
				//разбиваю все значения на строки
				$array_in_rows = array_chunk($_POST['data'], $_POST['quantity']);
				$sql_columns = $new_rows = $input_sql = '';
				
				$a = 1;
				
				foreach( $array_in_rows as $i => $data ) {
					$new_rows 		.= '<tr>';
					$input_sql 		.= '(';
					$sql_vals 		= '';
					
					foreach( $data as $i => $data_info ) {
						if($a == 1)
							$sql_columns .= $data_info['name'].', ';
							
						$new_rows		.= '<td class="'.$data_info['name'].'">'.$data_info['value'].'</td>';
						$sql_vals		.= "'{$data_info['value']}'".', ';
					}
					
					$a++;
					
					$input_sql .= substr($sql_vals, 0, -2).'),';
					$new_rows .= '<td class="edit_cancel_row">
									<div class="td_buttons">
										<span class="edit"></span>
										<span class="del_row"></span>
									</div>
								</td>
							</tr>';
				}
				
				$sql_columns 	= substr($sql_columns, 0, -2);
				$input_sql		= substr($input_sql, 0, -1);
				
				$sql = "insert into {$_POST['table']} ({$sql_columns}) values {$input_sql}";
				$conn->query($sql);
				
				foreach($conn->errors as $error) {
					$errors[] = $error;
				}

				echo json_encode( array( 'errors' => $conn->errors , 'data' => $new_rows ) );
			}
		break;
	}

?>